package com.lry.netty01.server.in;

import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.utils.ByteUtils;
import com.lry.netty01.server.utils.CommandUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 解码器，把buf解码成固定报文，相当于反序列化
 */
@Slf4j
public class PacketDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        log.info("客户端接收到报文："+ByteUtils.preBuf(buf));

        byte start = buf.getByte(buf.readerIndex());

        if(start== CommandUtil.START){
            buf.readByte();
            FixedFrame fixedFrame = new FixedFrame();

            byte cmd = buf.readByte();
            fixedFrame.setCmd(cmd);

            short devId = buf.readShort();
            fixedFrame.setDevId(devId);

            byte data = buf.readByte();
            fixedFrame.setData(data);

            byte cs = buf.readByte();
            byte calCs = ByteUtils.getCS(cmd,devId,data);
            if(cs!=calCs){
                log.info(devId+" cs出错，丢弃报文");
                buf.clear();
                return;
            }
            fixedFrame.setCs(cs);

            byte end = buf.readByte();
            if(end!=CommandUtil.END){
                log.info(devId+" 报尾出错，丢弃报文");
                buf.clear();
                return;
            }

            out.add(fixedFrame);
        }else{
            buf.clear();
        }

    }

}
